package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.xyy.XyyProduct;
import com.atmilan.quartz.model.entity.xyy.XyyProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceXyyProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildXyyProduct(XyyProduct product, List<XyyProductSku> productSkus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            JSONArray gallery = null == JSONArray.parseArray(product.getDetailImage()) ? new JSONArray() : JSONArray.parseArray(product.getDetailImage());
            // 成本价
            BigDecimal erpPrice = product.getOzUserPrice();
            // 售价
            BigDecimal adjustPrice = PriceUtil.hk2Rmb(product.getUserPrice());
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getOtherId, product.getBrandId())
                    .eq(StoreBrand :: getType, ProductTypeEnum.XYY)
                    .last("LIMIT 1")
                    );
            storeBrandService.unMatchBrand(buyerStoreBrand,product.getBrandId(),product.getBrandName(),ProductTypeEnum.XYY);
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
                storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
            } else {
                storeBrand = storeBrandService.getById(5429);
            }
//             处理单独品牌价格(无法做成配置的)
            if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
                adjustPrice = PriceUtil.calePrice(erpPrice, "0.65");
            }
            
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.XYY.getCode() + product.getGoodsId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            for(XyyProductSku sku : productSkus) {
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getSpecId());
                storeProductAttrValue.setSuk(sku.getSizeName());
                storeProductAttrValue.setStock(sku.getStock());
                storeProductAttrValue.setPrice(adjustPrice);
                if(gallery.size() > 0) {
                    storeProductAttrValue.setImage(gallery.get(0).toString());
                }
                storeProductAttrValue.setCost(adjustPrice);
                storeProductAttrValue.setSourceCost(adjustPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(erpPrice);
                
                storeProductAttrValue.setTempId(sku.getShId().equals("2") ? 2 : 1);
                
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getSizeName())) {
                    linkedMap.put("尺寸", sku.getSizeName());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
                // attr对象
                if(CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSizeName());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSizeName());
                }
            }
            
            productRequest = new StoreProductCrmebRequest();
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.XYY.getMerchantId());
//            productRequest.setContent(product.getDescription());
            productRequest.setKeyword(product.getSn());
            productRequest.setContent(product.getMianliao());
            productRequest.setStoreInfo(product.getMianliao());
            productRequest.setStoreName(product.getGoodsName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(erpPrice);
            productRequest.setCost(adjustPrice);
            productRequest.setSourceCost(adjustPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(2);
            
            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.XYY.getCode())
                    .last("LIMIT 1")
                    );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.XYY)
                    .eq(CategoryMatch :: getOthCategoryId, product.getCateId())
                    .eq(CategoryMatch :: getOthCategoryType, product.getKuanshi())
                    .last("LIMIT 1")
                    );
            categoryMatchService.unMatchCategory(categoryMatch,product.getCateId(),product.getKuanshi(),null,CategoryTypeEnum.XYY);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setImage(product.getDefaultImage());
            if(gallery.size() > 0) {
                productRequest.setSliderImage(gallery.toJSONString());
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.XYY.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }

}
